<?php

class ProductAction extends Action {

	private $insertStatement;
	private $listPackageTypeIdsStatement;
	private $getPackageTypeNameStatement;

	function __construct(){
		parent::__construct();
		$this->insertStatement = parent::prepareStatement("INSERT INTO products (package_unit_id, name, `natrium / 100g`,  `kCal / 100g`) VALUES (?,?,?,?)");
		$this->listPackageTypeIdsStatement = parent::prepareStatement("select package_unit_id, concat( p.name, ' (', p.quantity,  m.name, ')') as package_unit  from packageunits p, metricsystemunits m where m.metric_system_unit_id = p.metric_system_unit_id");
		$this->getPackageTypeNameStatement = parent::prepareStatement("select concat( p.name, ' (', p.quantity,  m.name, ')') as package_unit from packageunits p, metricsystemunits m where m.metric_system_unit_id = p.metric_system_unit_id and p.package_unit_id = ?");
	}
	
	function listPackageTypeIds(){
		$this->listPackageTypeIdsStatement->execute();
		$this->listPackageTypeIdsStatement->bind_result($package_unit_id, $package_unit);

		$resultSet = array();
		while ($this->listPackageTypeIdsStatement->fetch()) {
			array_push($resultSet, array($package_unit_id, $package_unit));
		}
		return $resultSet;
	}
	
	function insert($packageUnitId, $productName, $natrium = null, $kCal = null){
		if(!$packageUnitId){
			throw new Exception('package_unit_id cannot be null.');
		}
		if(!$productName){
			throw new Exception('productName cannot be null.');
		}
		
		$rc = $this->insertStatement->bind_param("isii", $packageUnitId, $productName, $natrium, $kCal);
		if ( false===$rc ) {
            printf('bind_param failed: %s', htmlspecialchars($this->insertStatement->error));
			die;
        }
		
		$rc = $this->insertStatement->execute();
        if ( false===$rc ) {
                printf('execute failed: %s', htmlspecialchars($this->insertStatement->error));
                die;
        }
	}
	
	function getPackageTypeName($packageTypeId){
		$rc = $this->getPackageTypeNameStatement->bind_param("i", $packageTypeId);
		if ( false===$rc ) {
            printf('bind_param failed: %s', htmlspecialchars($this->getPackageTypeNameStatement->error));
			die;
        }
		
		$this->getPackageTypeNameStatement->execute();
		$this->getPackageTypeNameStatement->bind_result($package_unit);

		$resultSet = array();
		while ($this->getPackageTypeNameStatement->fetch()) {
			array_push($resultSet, array($package_unit));
		}
		if(sizeof($resultSet) > 1){
			throw new Exception("Multiple values found for package type id (" . $packageTypeId . ")");
		}
		return $resultSet[0][0];
	}
}